package com.back.end.Service.impl;

import com.back.end.Dao.AppUserDao;
import com.back.end.Modal.Address;
import com.back.end.Modal.User;
import com.back.end.Service.AppUserService;
import com.back.end.enums.ResultCode;
import com.back.end.exception.AuthException;
import com.back.end.interceptor.JwtInterceptor;
import com.back.end.utils.redis.RedisUtil;
import com.back.end.utils.msg.SmsUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class AppUserServiceImpl implements AppUserService {
    @Resource
    AppUserDao appUserDao;

    @Resource
    RedisUtil redisUtil;


    @Override
    public User find_user(User user) {
        User u = appUserDao.find_user(user.getPhone());
        return u;
    }


    @Override
    public boolean sendSms(String phone, String code) throws TencentCloudSDKException {
        Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);
        SmsUtil smsUtil = new SmsUtil();
        Credential cred = new Credential(smsUtil.getSecretID(), smsUtil.getSecretKey());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
        SendSmsRequest req = new SendSmsRequest();

        String sdkAppId = smsUtil.getAppId();
        req.setSmsSdkAppId(sdkAppId);

        String signName = smsUtil.getSignName();
        req.setSignName(signName);

        String templateId = smsUtil.getTemplateId();
        req.setTemplateId(templateId);

        /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
        String[] templateParamSet = {code, "3"};
        req.setTemplateParamSet(templateParamSet);

        /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
         * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号 */
        String[] phoneNumberSet = {"+86" + phone};
        req.setPhoneNumberSet(phoneNumberSet);


        /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
         * 返回的 res 是一个 SendSmsResponse 类的实例，与请求对象对应 */
        SendSmsResponse res = client.SendSms(req);

        // 输出json格式的字符串回包
        logger.info(SendSmsResponse.toJsonString(res));

        Map<String, Object> info = new HashMap<>();
        info.put("phone", phone);
        info.put("code", code);
        redisUtil.set("code", code, 3);
        String value = redisUtil.getValue("code");
        logger.info(value);
        return true;
    }


    @Override
    public User smsLogin(String phone, String code, String name, String profile) {
        User u = new User();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        u.setPhone(phone);
        u.setName(name);
        u.setProfile(profile);
        if (redisUtil.get("code") == null) {
            throw new AuthException(ResultCode.SAFE_CODE_OVER_DATE);
        }
        if (redisUtil.getValue("code").equals(code)) {
            //查询是否存在此用户
            User find = find_user(u);
            if (find == null) {
                u.setCreatedTime(timestamp);
                appUserDao.userRegister(name, phone, timestamp, profile);
                return u;
            } else {
                return find;
            }
        } else {
            throw new AuthException(ResultCode.SAFE_CODE_ERROR);
        }
    }

    @Override
    public void addAddress(Address address) {
        appUserDao.addAddress(address.getName(), address.getCustomerId(), address.getPhone(), address.getAddress());
    }

    @Override
    public List<Address> getAddressList(int customerId) {
        List addressList = appUserDao.getAddressList(customerId);
        return addressList;
    }

    @Override
    public void updateAddress(Address address) {
        appUserDao.updateAddress(address.getId(), address.getName(), address.getPhone(), address.getAddress());
    }

    @Override
    public User checkUserInfo(String phone) {
        return appUserDao.find_user(phone);
    }

}
